//
//  HJPlayerView.m
//  project
//
//  Created by jc on 2019/4/23.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJPlayerView.h"
#import "AVPlayerManager.h"

@interface HJPlayerView () {
    NSString * _url;// 播放地址
}
@property (nonatomic,strong) AVPlayerItem * playItem;
@property (nonatomic,strong) AVPlayer * player;
@property (nonatomic,strong) AVPlayerLayer * playerLayer;
@property (nonatomic,assign) BOOL retried;
@property (nonatomic,strong) UIButton * pasueBtn;
@end


@implementation HJPlayerView

-(instancetype)initWithVideoUrl:(NSString *)url {
    if (self == [super init]) {
        
        _url = url;
        self.playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
        //初始化播放器
        _player = [AVPlayer playerWithPlayerItem:self.playItem];
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        //_playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
        _playerLayer.frame = [UIScreen mainScreen].bounds;
//        _playerLayer.backgroundColor = [UIColor redColor].CGColor;
        [self.layer insertSublayer:_playerLayer atIndex:0];
        [self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
        [_playerLayer.presentationLayer hitTest:[tap locationInView:self]];
        [self addGestureRecognizer:tap];
        
        self.pasueBtn.hidden = YES;
        [self addProgressObserver];
    }
    return self;
}
- (void)setVideoContent:(AVLayerVideoGravity)videoContent {
    _playerLayer.videoGravity = videoContent;
}



-(instancetype)Url {
    return [self initWithVideoUrl:@""];
}

-(void)tap:(UITapGestureRecognizer *)tap {
    [self updatePlayerState];
}
// 给AVPlayerLayer添加周期性调用的观察者，用于更新视频播放进度
-(void)addProgressObserver{
    __weak __typeof(self) weakSelf = self;
    //AVPlayer添加周期性回调观察者，一秒调用一次block，用于更新视频播放进度
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        if(weakSelf.playItem.status == AVPlayerItemStatusReadyToPlay) {
            //获取当前播放时间
            float current = CMTimeGetSeconds(time);
            //获取视频播放总时间
            float total = CMTimeGetSeconds([weakSelf.playItem duration]);
            //重新播放视频
            if(total == current) {
                [weakSelf replay];
            }
            //更新视频播放进度方法回调
            if(weakSelf.delegate) {
                [weakSelf.delegate onProgressUpdate:current total:total];
            }
        }
    }];
}

-(void)play {
    [[AVPlayerManager shareManager] play:self.player];
}
// 暂停
- (void)pause {
    [[AVPlayerManager shareManager] pause:self.player];
}
//重新播放
-(void)replay {
    [[AVPlayerManager shareManager] replay:self.player];
}
//更新AVPlayer状态，当前播放则暂停，当前暂停则播放
-(void)updatePlayerState {
    if(_player.rate == 0) {
        [self play];
    }else {
        [self pause];
    }
    self.pasueBtn.hidden = _player.rate == 0;
}
- (CGFloat)rate {
     return [_player rate];
}

//取消播放
-(void)cancelPlayer {
    //暂停视频播放
    [self pause];
    [_playerLayer setHidden:YES];
    _player = nil;
    [_playItem removeObserver:self forKeyPath:@"status"];
    _playItem = nil;
    _playerLayer.player = nil;
    _retried = NO;
    [self removeFromSuperview];
}
// 重新加载播放
-(void)retry {
    [self cancelPlayer];
    self.playItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_url]];
    [self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.playItem];
    self.playerLayer.player = self.player;
    [self addProgressObserver];
    _retried = YES;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]) {
        if(_playItem.status == AVPlayerItemStatusFailed) {
            NSLog(@"description=%@",self.player.error.description);
            if(!_retried) {
                [self retry];
            }
        }
        //视频源装备完毕，则显示playerLayer
        if(_playItem.status == AVPlayerItemStatusReadyToPlay) {
            [self.playerLayer setHidden:NO];
        }
        //视频播放状体更新方法回调
        if(_delegate) {
            [_delegate onPlayItemStatusUpdate:_playItem.status];
        }
    }else {
        return [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc {
    [self.playItem removeObserver:self forKeyPath:@"status"];
}

/**
 暂停按钮
 @return pasueBtn
 */
-(UIButton *)pasueBtn {
    if (!_pasueBtn) {
        _pasueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pasueBtn setImage:setImage(@"pauseBtn") forState:0];
        _pasueBtn.adjustsImageWhenHighlighted = YES;
        _pasueBtn.frame = CGRectMake((SCREEN_WIDTH /2)-35, ((SCREEN_HEIGTH -Height_NavBar-Height_TabBar-40) /2), 70, 70);
        [_pasueBtn rounded:UIRectCornerAllCorners radius:35];
        [_pasueBtn setBackgroundColor:[UIColor colorWithHex:0x39C5BB]];
        @weakify(self)
        [[_pasueBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self updatePlayerState];
        }];
        [self addSubview:_pasueBtn];
        [self bringSubviewToFront:_pasueBtn];
    }
    return _pasueBtn;
}
@end

#define SR_W [UIScreen mainScreen].bounds.size.width
#define SR_H [UIScreen mainScreen].bounds.size.height

//@interface HJKSYPlayerView ()
//
///**
// 金山播放器
// */
//@property (strong, nonatomic) KSYMoviePlayerController *player;
//
///**
// 播放视频地址
// */
//@property (nonatomic,strong) NSString * videoUrl;
//
//@end
//
//
//@implementation HJKSYPlayerView
//
//-(instancetype)initWithVideoUrl:(NSString *)url {
//    if (self == [super init]) {
//        self.autoresizesSubviews = YES;
//        // 播放地址
//        self.videoUrl = url;
//        // 添加播放器到父视图
//        [self addSubview:self.player.view];
//    }
//    return self;
//}
//
///**
// 懒加载播放器
// @return KSYMoviePlayerController
// */
//-(KSYMoviePlayerController *)player {
//    if (!_player) {
//        _player = [[KSYMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:self.videoUrl]];
//        _player.view.backgroundColor = [UIColor blackColor];
//        [_player setBufferSizeMax:1];
//        _player.view.autoresizesSubviews = YES;
//        [_player.view setFrame:self.bounds];
//        _player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//        _player.shouldAutoplay = YES;
//        _player.shouldLoop = YES;
////        _player.scalingMode = MPMovieScalingModeAspectFit;
//        [_player prepareToPlay];
//    }
//    return _player;
//}
//
///**
// 播放
// */
//-(void)play {
//    [self.player play];
//}
//
///**
// 暂停播放
// */
//-(void)pause {
//    [self.player pause];
//}
//
///**
// 暂停播放
// */
//-(void)stop {
//    [self.player stop];
//}
//
////取消播放
//-(void)cancelPlayer {
//    //暂停视频播放
//    [_player reset:false];
//    [self stop];
//    [_player.view removeFromSuperview];
//    _player = nil;
//    [self removeFromSuperview];
//}

//@end


